from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, timezone
from fsrs import Card as FSRSCard, State


db = SQLAlchemy()


class Card(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    grade = db.Column(db.String(50), nullable=False)  # 年级字段
    subject = db.Column(db.String(100), nullable=False)  # 学科字段
    class_name = db.Column(db.String(100), nullable=False)  # 班级字段
    question = db.Column(db.String(500), nullable=False)
    answer = db.Column(db.String(1000))
    due = db.Column(db.DateTime, nullable=False)
    stability = db.Column(db.Float, default=0)
    difficulty = db.Column(db.Float, default=0)
    state = db.Column(db.Integer, default=1)
    last_review = db.Column(db.DateTime)
    create_time = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))

    def to_fsrs(self):
        fsrs_card = FSRSCard()
        fsrs_card.due = self.due
        fsrs_card.stability = self.stability if self.stability else None
        fsrs_card.difficulty = self.difficulty if self.difficulty else None
        fsrs_card.state = self.state
        fsrs_card.last_review = (
            self.last_review.replace(tzinfo=timezone.utc) if self.last_review else None
        )
        return fsrs_card


class ReviewLog(db.Model):
    __bind_key__ = "reviews"  # 指定使用第二个数据库
    id = db.Column(db.Integer, primary_key=True)
    card_id = db.Column(db.Integer, nullable=False)
    rating = db.Column(db.Integer, nullable=False)
    review_time = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
    feedback = db.Column(db.String(500))  # 反馈字段